import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 用户信息
  const user = ref(null)
  const token = ref(localStorage.getItem('token') || '')
  const refreshToken = ref(localStorage.getItem('refresh_token') || '')
  const isLoggedIn = ref(!!localStorage.getItem('token'))

  // 登录
  const login = (userData, userToken, userRefresh) => {
    user.value = userData
    token.value = userToken
    refreshToken.value = userRefresh
    isLoggedIn.value = true
    
    // 保存到 localStorage
    localStorage.setItem('token', userToken)
    localStorage.setItem('refresh_token', userRefresh)
    localStorage.setItem('user', JSON.stringify(userData))
  }

  // 登出
  const logout = () => {
    user.value = null
    token.value = ''
    refreshToken.value = ''
    isLoggedIn.value = false
    
    // 清除 localStorage
    localStorage.removeItem('token')
    localStorage.removeItem('refresh_token')
    localStorage.removeItem('user')
  }

  // 更新用户信息
  const updateUser = (userData) => {
    user.value = { ...user.value, ...userData }
    localStorage.setItem('user', JSON.stringify(user.value))
  }

  // 从 localStorage 恢复用户信息
  const restoreUser = () => {
    const savedUser = localStorage.getItem('user')
    if (savedUser) {
      try {
        user.value = JSON.parse(savedUser)
      } catch (e) {
        console.error('Failed to parse saved user:', e)
      }
    }
  }

  // 设置 tokens（用于钉钉登录等场景）
  const setTokens = (accessToken, refreshTokenValue) => {
    token.value = accessToken
    refreshToken.value = refreshTokenValue
    isLoggedIn.value = true
    
    // 保存到 localStorage
    localStorage.setItem('token', accessToken)
    if (refreshTokenValue) {
      localStorage.setItem('refresh_token', refreshTokenValue)
    }
  }

  // 初始化时恢复用户信息
  restoreUser()

  return {
    user,
    token,
    refreshToken,
    isLoggedIn,
    login,
    logout,
    updateUser,
    restoreUser,
    setTokens
  }
})


